package exa.unicen.edu.ringo.raccess;

import java.io.IOException;
import java.net.URI;

import javax.ws.rs.core.UriBuilder;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.glassfish.grizzly.http.server.HttpServer;

import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;

import exa.unicen.edu.ringo.raccess.model.manager.ConfigurationManager;
import exa.unicen.edu.ringo.rmodel.constants.DefaultOptions;

public class App 
{

	public static void main(String[] args) throws IOException, ParseException {
		// OPTIONS
		Options options = new Options();
		options.addOption("h", true, String.format("web server host [%s]", DefaultOptions.RACCESS_HOST));
		options.addOption("p", true, String.format("web server port [%s]", DefaultOptions.RACCESS_PORT));
		options.addOption("c", true, "configuration file");
		
		// OPTIONS PARSER
		CommandLineParser parser = new PosixParser();
		CommandLine command = parser.parse(options, args);
		
		String host = command.hasOption("h") ? command.getOptionValue("h") : DefaultOptions.RACCESS_HOST;
		int port 	= command.hasOption("p") ? Integer.valueOf(command.getOptionValue("p")) : DefaultOptions.RACCESS_PORT;
		
		// INITIALIZE CONFIGURATION
		if (command.hasOption("c")) { 
			ConfigurationManager.instance.load(command.getOptionValue("c")); 
		} else {
			ConfigurationManager.instance.clear(); 
		}
		
		URI BASE_URI = UriBuilder.fromUri("http://"+host+"/").port(port).build();
		
		ResourceConfig rc = new PackagesResourceConfig("exa.unicen.edu.ringo.raccess.resources");
		HttpServer httpServer = GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
		System.in.read();
		httpServer.stop();
	}
}
